package com.seo.utils;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

public class WxPayUtil {

	public static String wxPayBack(String data, String pwd) throws Exception {
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		InputStream instream = WxPayUtil.class.getResourceAsStream("apiclient_cert.p12");
		try {
			keyStore.load(instream, pwd.toCharArray());
		} finally {
			instream.close();
		}

		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, pwd.toCharArray()).build();

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.getDefaultHostnameVerifier());

		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");

		String res = null;
		CloseableHttpResponse response = null;
		try {
			httpPost.setEntity(new StringEntity(data, "UTF-8"));
			response = httpClient.execute(httpPost);

			InputStream in = response.getEntity().getContent();
			res = IOUtils.toString(in, "UTF-8");
			in.close();
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return res;

	}

	public static void main(String args[]) {
		try {
			System.out.println(wxPayBack("wwwww","1513733931"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
